namespace Xmef.Library
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Reflection;
    using System.Text;

    public static class TypeHelper
    {
        public static string GetHostName(string host, MemberInfo service)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}({1})", new object[] { host, service.Name });
        }

        public static StringBuilder GetServiceName(Type service)
        {
            StringBuilder name = new StringBuilder();
            if (service.IsGenericType)
            {
                IEnumerable<Type> arguments = service.GetGenericArguments();
                IEnumerator<Type> enumerator = arguments.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    name.Append(service.Name);
                    name.Append("[");
                    name.Append(enumerator.Current.Name);
                    while (enumerator.MoveNext())
                    {
                        name.Append(",");
                        name.Append(enumerator.Current.Name);
                    }
                    name.Append("]");
                }
                return name;
            }
            name.Append(service.Name);
            return name;
        }

        public static bool HasDefaultConstructor(Type type)
        {
            return (type.GetConstructor(Type.EmptyTypes) != null);
        }

        public static bool IsSubClass<T>(Type supertype)
        {
            return IsSubClass(typeof(T), supertype);
        }

        public static bool IsSubClass(Type subtype, Type supertype)
        {
            return ((subtype.IsAssignableFrom(supertype) && !supertype.IsAbstract) && supertype.IsClass);
        }

        public static bool IsSubtype<T>(Type supertype)
        {
            return IsSubtype(typeof(T), supertype);
        }

        public static bool IsSubtype(Type subtype, Type supertype)
        {
            return subtype.IsAssignableFrom(supertype);
        }
    }
}

